package com.zhongshengnetwork.rightbe.wzt.view;

import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.BezierRadarHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.Constant.Constant;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.BaseAnalyticsFragment;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.ScreenUtils;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.gsonmodel.WeiShuInfoDetailModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;
import com.zhongshengnetwork.rightbe.wzt.activity.ClassifyActivity;
import com.zhongshengnetwork.rightbe.wzt.activity.WZTActivity;
import com.zhongshengnetwork.rightbe.wzt.activity.WZTListActivity;
import com.zhongshengnetwork.rightbe.wzt.activity.WZTSearchActivity;
import com.zhongshengnetwork.rightbe.wzt.model.WZTUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MyWZTFragment extends BaseAnalyticsFragment {

    private final int linecount = 3;
    public String userid = null;
    public int dataType = 0;
    private int pageindex = 0;
    private static final int Records = 20;
    private boolean isHasMore = false;
    private List<WeiShuInfoDetailModel> list;
    private ListView listview;
    private MyAdapter adapter;
    private View rootView;//缓存Fragment view
    private int imgW = 0;
    private boolean isGetting = false;
    private ImageView no_data_img;
    private RefreshLayout mRefreshLayout;

    private RelativeLayout search_top;
    private LinearLayout my_classify_layout;

    private void calculateImageWidth(){
        int width = ScreenUtils.getScreenWidth(getActivity());
        float density = ScreenUtils.getScreenDensity(getActivity());
        imgW = (int) ((width-40*density)/linecount);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        calculateImageWidth();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        if (rootView == null) {
            rootView = inflater.inflate(R.layout.my_wzt_layout, container, false);
            pageindex = 0;
            if (list == null){
                list = new ArrayList<WeiShuInfoDetailModel>();
                int width = ScreenUtils.getScreenWidth(getActivity());
                float density = ScreenUtils.getScreenDensity(getActivity());
                imgW = (int) ((width-40*density)/linecount);
            }
            no_data_img = (ImageView)rootView.findViewById(R.id.no_data_img);
            listview=(ListView) rootView.findViewById(R.id.wzt_listview);
            adapter=new MyAdapter();
            listview.setAdapter(adapter);
            listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Log.e("TAG","position="+position);
                }
            });

            my_classify_layout = (LinearLayout) rootView.findViewById(R.id.my_classify_layout);
            my_classify_layout.setClickable(true);
            my_classify_layout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (getActivity() != null){
                        Intent intent = new Intent(getActivity(), ClassifyActivity.class);
                        intent.putExtra("title","我的分类");
                        startActivity(intent);
                    }
                }
            });

            mRefreshLayout = rootView.findViewById(R.id.refreshLayout);
            //设置 Header 为 贝塞尔雷达 样式
            mRefreshLayout.setRefreshHeader(new BezierRadarHeader(getActivity()).setEnableHorizontalDrag(true));//BezierRadarHeader
            //设置 Footer 为 球脉冲 样式
            mRefreshLayout.setRefreshFooter(new ClassicsFooter(getActivity()).setSpinnerStyle(SpinnerStyle.FixedBehind));//BallPulseFooter ClassicsFooter
            mRefreshLayout.setPrimaryColors(AppThemeUtils.getInstance().getRefreshBackgroundColor(),AppThemeUtils.getInstance().getRefreshAccessColor());
            mRefreshLayout.setEnableRefresh(true);//启用刷新
            mRefreshLayout.setEnableLoadMore(false);//启用加载
            //刷新
            mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
                @Override
                public void onRefresh(RefreshLayout refreshlayout) {
                    //refreshlayout.finishRefresh();
                    pageindex = 0;
                    getData();
                }
            });
            mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
                @Override
                public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                    //refreshLayout.finishLoadMore();
                    getData();
                }
            });

            search_top = (RelativeLayout) rootView.findViewById(R.id.search_top);
            search_top.setClickable(true);
            search_top.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (getActivity() == null){
                        return;
                    }
                    if (dataType != 1 && CommonUtils.isEmpty(userid)){
                        //获取我的
                        Intent intent = new Intent(getActivity(), WZTListActivity.class);
                        intent.putExtra("title","我的微纸条");
                        intent.putExtra("dataType",1001);
                        startActivity(intent);
                        return;
                    }
                    Intent intent = new Intent(getActivity(), WZTSearchActivity.class);
                    startActivity(intent);
                }
            });

            RelativeLayout my_wzt_layout = (RelativeLayout) rootView.findViewById(R.id.my_wzt_layout);
            my_wzt_layout.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
            listview.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
            listview.setDivider(new ColorDrawable(AppThemeUtils.getInstance().getMainColor()));
            listview.setDividerHeight(AppThemeUtils.DividerHeight);

            LinearLayout top_layout = (LinearLayout) rootView.findViewById(R.id.top_layout);
            top_layout.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
            search_top.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
            my_classify_layout.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
            TextView classify_text = (TextView) rootView.findViewById(R.id.classify_text);
            classify_text.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
            RelativeLayout search_shape_layout = (RelativeLayout) rootView.findViewById(R.id.search_shape_layout);
            search_shape_layout.setBackgroundResource(AppThemeUtils.getInstance().getSearchBackground());


            getData();
        }else {
            //缓存的rootView需要判断是否已经被加过parent， 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (parent != null) {
                parent.removeView(rootView);
            }
        }

        return rootView;
    }

    public void getFirstData(boolean isFirst){
        if (listview == null || list == null){
            return;
        }
        if (list.size() == 0){
            //listview.startRefresh();
            if (mRefreshLayout != null){
                pageindex = 0;
                mRefreshLayout.autoRefresh();
            }
        }else {
            if (isFirst == true){
                //listview.smoothScrollToPosition(0);
                listview.setSelection(0);
            }
        }
    }

    public void updateData(){
        if (listview == null || list == null){
            return;
        }
        if (mRefreshLayout != null){
            pageindex = 0;
            mRefreshLayout.autoRefresh();
        }
    }

    private void getData(){
        if (listview == null){
            return;
        }
        if (isGetting == true){
            if (mRefreshLayout.getState() == RefreshState.Refreshing){
                mRefreshLayout.finishRefresh();
            }else {
                mRefreshLayout.finishLoadMore();
            }
            return;
        }
        isGetting = true;
        new Thread(){
            @Override
            public void run() {
                super.run();
                final HashMap<String, String> map = new HashMap<String, String>();
                String url = "weishu/theme/user/list.do";
                map.put(APIKey.tokenKey, CommonUtils.formatString(CustomApplication.loginModel.getToken()));
                if (dataType == 1){//最新
                    url = "weishu/theme/latest/list.do";
                }else {
                    map.put("dataUserId",userid);
                }
                map.put("pageIndex",pageindex+"");
                map.put("pageRecord",Records+"");
                HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                    @Override
                    public void onSuccess(String data) {
                        Log.e("微纸条",data+"\n");
                        isGetting = false;
                        if (getActivity() == null){
                            return;
                        }
                        CommonModel commonModel = GsonTools.getCommonModel(data);
                        if (commonModel.getFlag().equals("1")){
                            List<WeiShuInfoDetailModel> l = GsonTools.getWeiShuInfoDetailModel(data);
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (mRefreshLayout.getState() == RefreshState.Refreshing){
                                        mRefreshLayout.finishRefresh();
                                        list.clear();
                                    }else {
                                        mRefreshLayout.finishLoadMore();
                                    }
                                    if (l != null && l.size() > 0){
                                        no_data_img.setVisibility(View.INVISIBLE);
                                        if (l.size() >= Records){
                                            //listview.setPullLoadEnable(true);
                                            mRefreshLayout.setEnableLoadMore(true);
                                        }else {
                                            //listview.setPullLoadEnable(false);
                                            mRefreshLayout.setEnableLoadMore(false);
                                        }
                                        list.addAll(l);
                                        //Log.e("微纸条","数据大小="+list.size()+"\n");
                                    }else {
                                        isHasMore = false;
                                        //listview.setPullLoadEnable(false);
                                        mRefreshLayout.setEnableLoadMore(false);
                                    }
                                    adapter.notifyDataSetChanged();
                                    if (pageindex == 0){
                                        //listview.smoothScrollToPosition(0);
                                        listview.setSelection(0);
                                    }
                                    pageindex += 1;
                                }
                            });
                        }else {
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (mRefreshLayout.getState() == RefreshState.Refreshing){
                                        mRefreshLayout.finishRefresh();
                                        list.clear();
                                    }else {
                                        mRefreshLayout.finishLoadMore();
                                    }
                                    CustomApplication.showTip(commonModel, getActivity());
                                }
                            });
                        }
                    }

                    @Override
                    public void onError(String msg) {
                        isGetting = false;
                        if (getActivity() != null){
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (mRefreshLayout.getState() == RefreshState.Refreshing){
                                        mRefreshLayout.finishRefresh();
                                    }else {
                                        mRefreshLayout.finishLoadMore();
                                    }
                                }
                            });
                        }
                    }
                });
            }
        }.start();

    }

    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            int count = list.size()/linecount;
            if (list.size()%linecount > 0){
                count += 1;
            }
            return count;
        }


        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public boolean isEnabled(int position) {
            // TODO Auto-generated method stub
            return super.isEnabled(position);
        }

        /**
         * @param position
         * @param convertView
         * @param parent
         * @return
         */
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            //convertView的复用
            if (convertView == null) {
                convertView = View.inflate(getActivity(), R.layout.wzt_listview_item,null);
            }
            View view=convertView;

            LinearLayout wzt_layout_1 = (LinearLayout) view.findViewById(R.id.wzt_layout_1);
            LinearLayout wzt_layout_2 = (LinearLayout) view.findViewById(R.id.wzt_layout_2);
            LinearLayout wzt_layout_3 = (LinearLayout) view.findViewById(R.id.wzt_layout_3);

            ImageView wzt_img1 = (ImageView) view.findViewById(R.id.wzt_img1);
            TextView wzt_readcount_1 = (TextView) view.findViewById(R.id.wzt_readcount_1);
            TextView private_text_1 = (TextView) view.findViewById(R.id.private_text_1);
            TextView wzt_text1 = (TextView) view.findViewById(R.id.wzt_text1);


            ImageView wzt_img2 = (ImageView) view.findViewById(R.id.wzt_img2);
            TextView wzt_readcount_2 = (TextView) view.findViewById(R.id.wzt_readcount_2);
            TextView private_text_2 = (TextView) view.findViewById(R.id.private_text_2);
            TextView wzt_text2 = (TextView) view.findViewById(R.id.wzt_text2);

            ImageView wzt_img3 = (ImageView) view.findViewById(R.id.wzt_img3);
            TextView wzt_readcount_3 = (TextView) view.findViewById(R.id.wzt_readcount_3);
            TextView private_text_3 = (TextView) view.findViewById(R.id.private_text_3);
            TextView wzt_text3 = (TextView) view.findViewById(R.id.wzt_text3);

            wzt_img1.setVisibility(View.GONE);
wzt_layout_1.setVisibility(View.GONE);
            wzt_readcount_1.setVisibility(View.GONE);
            private_text_1.setVisibility(View.GONE);
            wzt_text1.setVisibility(View.GONE);


wzt_img2.setVisibility(View.GONE);
wzt_layout_2.setVisibility(View.GONE);
            wzt_readcount_2.setVisibility(View.GONE);
            private_text_2.setVisibility(View.GONE);
            wzt_text2.setVisibility(View.GONE);

            wzt_img3.setVisibility(View.GONE);
wzt_layout_3.setVisibility(View.GONE);
            wzt_readcount_3.setVisibility(View.GONE);
            private_text_3.setVisibility(View.GONE);
            wzt_text3.setVisibility(View.GONE);

            LinearLayout wzt_listview_item_layout = (LinearLayout) view.findViewById(R.id.wzt_listview_item_layout);
            wzt_listview_item_layout.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
            wzt_text1.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
            wzt_text2.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
            wzt_text3.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
            wzt_img1.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
            wzt_img2.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
            wzt_img3.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());

            Log.e("微纸条","position="+position+"\n");

            int num = 0;
            int count = linecount*position;
            if (list.size()-count >= linecount){
                num = linecount;
            }else {
                while (list.size()-count > 0){
                    num+=1;
                    count+=1;
                }
            }
            int index = linecount*position;
            RequestOptions options = new RequestOptions().error(AppThemeUtils.getInstance().getDefaultImageBg()).bitmapTransform(new RoundedCorners(Constant.CornerRadius));//图片圆角
            for (int i = 0; i < num; i++){
                WeiShuInfoDetailModel model = list.get(index+i);
                Log.e("微纸条","标题="+model.getTitle()+"\n");
                if (i == 0){
                    wzt_img1.setVisibility(View.VISIBLE);
wzt_layout_1.setVisibility(View.VISIBLE);
                    wzt_readcount_1.setVisibility(View.VISIBLE);
                    wzt_text1.setVisibility(View.VISIBLE);
                    ViewGroup.LayoutParams params = wzt_img1.getLayoutParams();
                    params.width =imgW;
                    params.height = imgW;
                    wzt_img1.setLayoutParams(params);
                    params = wzt_text1.getLayoutParams();
                    params.width = imgW;
                    wzt_text1.setLayoutParams(params);

                    Glide.with(getActivity()).load(model.getCover()).apply(options).placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).dontAnimate().into(wzt_img1);
                    wzt_text1.setText(model.getTitle());
                    wzt_readcount_1.setText(CommonUtils.getDisplayCount(model.getRealcount()));
                    if (model.getVisible() == false){
                        private_text_1.setVisibility(View.VISIBLE);
                    }

                    wzt_layout_1.setTag(index+i);
                    wzt_layout_1.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            onClickItem(v);
                        }
                    });

                }else if (i == 1){
                    wzt_img2.setVisibility(View.VISIBLE);
wzt_layout_2.setVisibility(View.VISIBLE);
                    wzt_readcount_2.setVisibility(View.VISIBLE);
                    wzt_text2.setVisibility(View.VISIBLE);
                    ViewGroup.LayoutParams params = wzt_img2.getLayoutParams();
                    params.width =imgW;
                    params.height = imgW;
                    wzt_img2.setLayoutParams(params);
                    params = wzt_text2.getLayoutParams();
                    params.width = imgW;
                    wzt_text2.setLayoutParams(params);
                    Glide.with(getActivity()).load(model.getCover()).apply(options).placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).dontAnimate().into(wzt_img2);
                    wzt_text2.setText(model.getTitle());
                    wzt_readcount_2.setText(CommonUtils.getDisplayCount(model.getRealcount()));
                    if (model.getVisible() == false){
                        private_text_2.setVisibility(View.VISIBLE);
                    }
                    wzt_layout_2.setTag(index+i);
                    wzt_layout_2.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            onClickItem(v);
                        }
                    });
                }else if (i == 2){
                    wzt_img3.setVisibility(View.VISIBLE);
wzt_layout_3.setVisibility(View.VISIBLE);
                    wzt_readcount_3.setVisibility(View.VISIBLE);
                    wzt_text3.setVisibility(View.VISIBLE);
                    ViewGroup.LayoutParams params = wzt_img3.getLayoutParams();
                    params.width =imgW;
                    params.height = imgW;
                    wzt_img3.setLayoutParams(params);
                    params = wzt_text3.getLayoutParams();
                    params.width = imgW;
                    wzt_text3.setLayoutParams(params);
                    Glide.with(getActivity()).load(model.getCover()).apply(options).placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).dontAnimate().into(wzt_img3);
                    wzt_text3.setText(model.getTitle());
                    wzt_readcount_3.setText(CommonUtils.getDisplayCount(model.getRealcount()));
                    if (model.getVisible() == false){
                        private_text_3.setVisibility(View.VISIBLE);
                    }
                    wzt_layout_3.setTag(index+i);
                    wzt_layout_3.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            onClickItem(v);
                        }
                    });
                }
            }
            return view;
        }
    }

    private void onClickItem(View v){

        WeiShuInfoDetailModel model = list.get((int)v.getTag());
        /*
        CustomDialog dialog = null;
        final CustomDialog.Builder builder = new CustomDialog.Builder(getActivity());
        builder.setTitle(model.getTitle());
        builder.setMessage(model.getDetail());
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog = builder.create();
        dialog.show();
        */
        Log.e("详情",model.getTitle()+"\n");

        WZTUtils.goToWZT(getActivity(), model);

    }

}

